import {NbGoStep} from '../NbGoStep.js';
import {normalizeConfigValue} from '../GoUtils.js';
import {StrUtil} from '../../../utils/StrUtil.js';

function resolvePlanId(context) {
    if (context.cache.planId) {
        return context.cache.planId;
    }
    const metadata = context.stateManager.getMetadata('createPlan');
    if (metadata?.planId) {
        return metadata.planId;
    }
    return null;
}

export class ConfirmPlanRequirementStep extends NbGoStep {
    constructor() {
        super({
            key: 'confirmPlanRequirement',
            name: '发布计划需求确认',
            description: '调用需求确认接口完成发布计划校验'
        });
    }

    async shouldSkip(context, state) {
        if (state?.status === 'completed') {
            return {
                skip: true,
                reason: '需求确认已完成',
                metadata: state.metadata
            };
        }
        const planId = resolvePlanId(context);
        if (!planId) {
            throw new Error('缺少发布计划 ID，请先执行创建发布计划步骤');
        }
        context.cache.planId = planId;
        return {skip: false};
    }

    async execute(context) {
        const {pipeline, opsClient, projectOpsFile} = context;
        const planId = resolvePlanId(context);
        if (!planId) {
            throw new Error('缺少发布计划 ID，无法执行需求确认');
        }
        const {flowId, flowType} = pipeline.getFlowIdentity();
        const confirmPayload = {
            id: planId,
            flow_id: flowId,
            flow_type: flowType
        };
        const extraRemark = normalizeConfigValue(projectOpsFile.read('flow.plan.confirm_remark'));
        if (StrUtil.notNull(extraRemark)) {
            confirmPayload.remark = extraRemark;
        }
        await opsClient.confirmFlowPlanRequirement(confirmPayload);
        // 再次读取以确保计划仍然有效
        await opsClient.getPlanRelease(planId);
        return {
            planId,
            finishedAt: new Date().toISOString()
        };
    }
}
